package com.ds.infrastructure.hyperspace.console.dto.apirouter;

import com.ds.infrastructure.hyperspace.console.dto.configdata.EndpointsDTO;
import com.ds.infrastructure.hyperspace.console.exceptions.HyperspaceException;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.ds.infrastructure.hyperspace.console.dto.configdata.ConfigDataDTO.ENDPOINT_TYPE.ENTRY;
import static com.ds.infrastructure.hyperspace.console.dto.configdata.ConfigDataDTO.ENDPOINT_TYPE.TARGET;

/**
 * @author: yaozhendong
 * @create: 2019-09-20 16:15
 **/
@Data
@NoArgsConstructor
public class ApiRouterEndpointsDTO implements Serializable {
    private List<ApiRouterEntryEndpointConfig> entryEndpoints = new ArrayList<>();

    private List<ApiRouterTargetEndpointConfig> targetEndpoints = new ArrayList<>();


    public static void toApiRouter(List<EndpointsDTO> dtoList, ApiRouterEndpointsDTO apiRouterEndpointsDTO) {
        //
        addEntryEndpoints(dtoList, apiRouterEndpointsDTO);
        //
        addTargetEndpoints(dtoList, apiRouterEndpointsDTO);
    }

    private static void addEntryEndpoints(List<EndpointsDTO> dtoList, ApiRouterEndpointsDTO apiRouterEndpointsDTO) {
        List<EndpointsDTO> entryEndpointsDTOList = dtoList.stream().filter(item -> ENTRY.value.equals(item.getType())).collect(Collectors.toList());
        if (entryEndpointsDTOList == null || entryEndpointsDTOList.isEmpty()) {
            throw new HyperspaceException("entry endpoints is empty");
        }
        List<ApiRouterEntryEndpointConfig> apiRouterEntryEndpointConfigList = new ArrayList<>();
        entryEndpointsDTOList.forEach(item -> apiRouterEntryEndpointConfigList.add(ApiRouterEntryEndpointConfig.toApiRouter(item)));
        apiRouterEndpointsDTO.getEntryEndpoints().addAll(apiRouterEntryEndpointConfigList);
    }

    private static void addTargetEndpoints(List<EndpointsDTO> dtoList, ApiRouterEndpointsDTO apiRouterEndpointsDTO) {
        List<EndpointsDTO> targetEndpointsDTOList = dtoList.stream().filter(item -> TARGET.value.equals(item.getType())).collect(Collectors.toList());
        if (targetEndpointsDTOList == null || targetEndpointsDTOList.isEmpty()) {
            throw new HyperspaceException("target endpoints is empty");
        }
        List<ApiRouterTargetEndpointConfig> apiRoutertargetEndpointConfigList = new ArrayList<>();
        targetEndpointsDTOList.forEach(item -> apiRoutertargetEndpointConfigList.add(ApiRouterTargetEndpointConfig.toApiRouter(item)));
        apiRouterEndpointsDTO.getTargetEndpoints().addAll(apiRoutertargetEndpointConfigList);
    }
}
